package com.cjh.mybatis11.executor;

import com.cjh.mybatis11.executor.statement.StatementHandler;
import com.cjh.mybatis11.mapping.BoundSql;
import com.cjh.mybatis11.mapping.MappedStatement;
import com.cjh.mybatis11.session.Configuration;
import com.cjh.mybatis11.session.ResultHandler;
import com.cjh.mybatis11.session.RowBounds;
import com.cjh.mybatis11.transaction.Transaction;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * @Descripton 简单执行器
 * @Author cjh
 * @Date 2023/6/1 10:27
 */
public class SimpleExecutor extends BaseExecutor {
    public SimpleExecutor(Configuration configuration, Transaction transaction) {
        super(configuration, transaction);
    }

    @Override
    protected int doUpdate(MappedStatement mappedStatement, Object parameter) throws SQLException {
        Statement statement = null;
        try {
            Configuration configuration1 = mappedStatement.getConfiguration();
            // 新建一个 StatementHandler
            StatementHandler handler = configuration1.newStatementHandler(this, mappedStatement, parameter, RowBounds.DEFAULT, null, null);

            // 准备语句
            Statement statement1 = prepareStatement(handler);
            // StatementHandler.update
            return handler.update(statement1);
        } finally {
            closeStatement(statement);
        }

    }

    @Override
    protected <E> List<E> doQuery(MappedStatement mappedStatement, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)
            throws SQLException {

        Statement statement  =null;

        try {
            Configuration configuration1 = mappedStatement.getConfiguration();

            // 新建一个 StatementHandler
            StatementHandler handler = configuration.newStatementHandler(this, mappedStatement, parameter, rowBounds, resultHandler, boundSql);


            // 准备语句
            statement = prepareStatement(handler);

            // 返回结果
            return handler.query(statement, resultHandler);

        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    private Statement prepareStatement(StatementHandler handler) throws SQLException {
        Statement statement;
        Connection connection = transaction.getConnection();
        //    准备语句
        statement = handler.prepare(connection);
        handler.parameterize(statement);

        return statement;
    }
}
